from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid, decode_openid
from apps.users.models import User
from meiduo_market.settings import QQ_CLIENT_ID, QQ_CLIENT_SECRET, QQ_REDIRECT_URI
from utils.response_code import RETCODE

# 点击qq登陆回发送ajax请求,跳转到这个路由视图函数,并把qqurl返回给前端
class QQLoginView(View):
    def get(self,request):
        state = 'zebinliu'
        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state=state)

        login_url = qq.get_qq_url()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})

# 登陆qq后会跳转到绑定用户界面
class QQcallbackView(View):
    def get(self,request):
        code = request.GET.get('code')
        state = request.GET.get('state')
        if code is None:
            return http.HttpResponseBadRequest('code参数不存在')

        # 生成qq_url
        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state=state)
        token = qq.get_access_token(code)

        openid= qq.get_open_id(token)

        # 查询有没有openid,如果有说明绑定过,跳转到主页
        # 如果没有查询到openid,说明没绑定过,到绑定界面
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 对openid进行加密
            access_token = generic_openid(openid)
            # return render(request,'oauth_callback.html',context={'openid': openid})
            return render(request, 'oauth_callback.html', context={'openid': access_token})
        else:
            # 设置登陆状态
            login(request, qquser.user)
            # 重定向到首页
            response = redirect(reverse('contents:index'))
            # 设置cookie,让首页显示用户名
            response.set_cookie('username', qquser.user.username, max_age=3600)
            return response

    def post(self,request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        access_token = request.POST.get('openid')
        # 解码openid
        openid = decode_openid(access_token)
        if not all([mobile,password,sms_code,access_token]):
            return http.HttpResponseBadRequest('参数不齐')
        import re
        if not re.match(r'1[3-9]\d{9}', mobile):
            return http.HttpResponseBadRequest('手机号不符合规则')
        # 验证密码是否符合规则
        if not re.match(r'[0-9A-Za-z]{8,20}', password):
            return http.HttpResponseBadRequest('密码不符合规则')

        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s'%mobile)
        if redis_sms_code is None:
            return http.HttpResponseBadRequest('短信验证码已经过期了')
        if redis_sms_code.decode().lower() != sms_code.lower():
            return http.HttpResponseBadRequest('短信验证码不正确')

        # 判断手机号在不在数据库中
        try:
            user = User.objects.get(mobile=mobile)
            # 如果不在说明没创建过,需要创建一个user对象
        except User.DoesNotExist:
            user = User.objects.create_user(uername=mobile,mobile=mobile,password=password)
            # 如果手机号存在,那么需要校验密码对不对
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('密码不正确')
        # 绑定openid和用户
        qquser = OAuthQQUser.objects.create(user=user,openid=openid)

        login(request,user)

        response = redirect(reverse('contents:index'))

        response.set_cookie('username',user.username,max_age=600)
        return response





